package com.pzh.logistics.shiro;


import com.pzh.logistics.exception.GlobalException;
import com.pzh.logistics.exception.ResultEnum;
import com.pzh.logistics.mbg.model.User;
import com.pzh.logistics.service.UserInfoService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

class UserRealm extends AuthorizingRealm {

    @Resource
    private UserInfoService userInfoService;

    // 9. 前面被authc拦截后，需要认证(校验登录)，SecurityBean会调用这里进行认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        if (token.getUsername() == null || token.getPassword() == null) {
            throw new GlobalException(ResultEnum.PARAM_ERROR);
        }
        // 9.1. 为了方便演示，我这里写死了用户admin-name密码admin-pwd才能登录
        User user = userInfoService.findByUsername(token.getUsername());

        String password = new String((char[])token.getPassword()); //得到密码
        if (user == null){
            throw new UnknownAccountException();
        }
        if (!user.getPassword().equals(password)){
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }


    // 10. 前面被roles拦截后，需要授权才能登录，SecurityManager需要调用这里进行权限查询
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行授权逻辑");

        // 10.1. 为了方便演示，这里直接写死返回了admin角色，所有能登录的角色都是admin了
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User userInfo  = (User)principals.getPrimaryPrincipal();
        authorizationInfo.addRole(userInfo.getRole());
        return authorizationInfo;
    }
}
